import {
  Component,
  OnInit,
  ElementRef,
  ViewChild,
  ViewChildren,
  AfterViewInit,
  Renderer,
  SimpleChanges,
  OnDestroy,
  QueryList
} from '@angular/core';
import {ApplicationService} from '../../../service/application.service';
import {DataSourceService} from '../../../service/data-source/data-source.service';
import {PowerDeviationTableComponent} from './power-deviation-table/power-deviation-table.component';
import {Table, TableRow, TableColomn, TableCell} from './table.model';
import {TagData} from '../../../entity/tag-data.model';
import {List} from 'linqts';
import {DatePipe} from '@angular/common';
import {Farm} from '../../../entity/farm.model';
import {FarmService} from '../../../service/farm.service';
import {QuotaRankService} from '../../../service/quota-rank.service';
import {PowerDeviation} from '../../../entity/power-deviation.model';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
  selector: 'app-power-forecast-deviation',
  templateUrl: './power-forecast-deviation.component.html',
  styleUrls: ['./power-forecast-deviation.component.css']
})
export class PowerForecastDeviationComponent implements OnInit {

  // 表格组件
  @ViewChildren(PowerDeviationTableComponent)
  deviationtables: QueryList<PowerDeviationTableComponent>;

  // 时间选择
  public date: Date = new Date();
  public years: string[] = ['2020', '2019', '2018', '2017', '2016', '2015'];
  public months: string[] = ['12', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1'];
  public currentYear: string;
  public startYear: string;
  public year: string;
  public currentMonth: string;
  public startMonth: string;
  public currentDay = new Date(this.date.getFullYear(), this.date.getMonth(), this.date.getDate() + 3);
  public startDay = new Date(this.date.getFullYear(), this.date.getMonth(), this.date.getDate() - 3);

  /**
   * 当前选中下标（年度、月度、季度）
   *
   * @type {number}
   * @memberof PowerForecastDeviationComponent
   */
  active: number = 1;

  /**
   * 生成表头
   *
   * @type {any[]}
   * @memberof PowerForecastDeviationComponent
   */
  public titles: string[] = [];

  //按风场区别之后的所有数据集合（日）
  private farmsPowersDatas: any[] = [];

  /**
   * 年度/月度/日对应数据集合
   *
   * @type {any[]}
   * @memberof PowerForecastDeviationComponent
   */
  public powersYear: PowerData[] = [];
  public powersMonth: PowerData[] = [];
  public powersDate: PowerData[] = [];

  // 风场数据集合
  farms: Farm[] = [];
  // 风场ids集合
  farmsId: number[] = [];
  /**
   * 倍率
   *
   * @public
   * @type {number}@memberof PowerForecastDeviationComponent
   */
  public ratio: number = 1;
  /**
   *日期格式化
   *
   * @type {*}
   * @memberof PowerForecastDeviationComponent
   */
  en: any;

  constructor(
    private farmService: FarmService,
    private dataSource: DataSourceService,
    private application: ApplicationService,
    private datePipe: DatePipe,
    private quotaRankService: QuotaRankService,
    private _message: NzMessageService
  ) {
  }

  tableRows: string[];
  tableRowsaaa: string[] = [];
  sales: any[];

  ngOnInit() {
    this.en = {
      firstDayOfWeek: 0,
      dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
      dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
      dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
      monthNames: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
      monthNamesShort: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'],
      today: '今天',
      clear: '清除'
    };
    if (this.application.currentApplicationParams && this.application.currentApplicationParams['ratio']) {
      this.ratio = Number(this.application.currentApplicationParams['ratio'].paramValue);
    }
    const cYear = this.date.getFullYear();
    const sYear = this.date.getFullYear() - 1;
    const cYIndex = this.years.findIndex(m => Number(m) === cYear);
    const sYIndex = this.years.findIndex(m => Number(m) === sYear);
    this.currentYear = this.years[cYIndex];
    this.startYear = this.years[sYIndex];
    this.year = this.startYear;
    const cMonth = this.date.getMonth() + 1;
    const sMonth = this.date.getMonth() - 1;
    const cIndex = this.months.findIndex(m => Number(m) === cMonth);
    const sIndex = this.months.findIndex(m => Number(m) === sMonth);
    this.currentMonth = this.months[cIndex];
    this.startMonth = this.months[sIndex];
    this.farmService.getFarmsWithTotalTurbineByUserId(this.application.currentUser.userId)
      .then(res => {
        this.farms = [...res];
        this.farmsId = this.farms.map(o => o.farmId);
        this.titles = this.farms.map(o => o.farmName);
        /* this.titles.sort(function (a, b) {
                    return a.localeCompare(b, "zh");
                }); */
        this.initPowersData(this.farmsId);
      })
      .catch(error => {
        console.log('app-power-forecast-deviation', error);
      });
  }

  onClickHeader(a: number) {
    if (a === 2) {
      this.startYear = this.currentYear;
    } else if (a === 3) {
      this.startYear = this.year;
    }
    this.active = a;
    this.initPowersData(this.farmsId);
  }

  public onChangeYear(event) {
    this.currentYear = event;
  }

  public onChangeStartYear(event) {
    this.startYear = event;
  }

  public onChangeMonth(event) {
    this.currentMonth = event;
  }

  public onChangeStartMonth(event) {
    this.startMonth = event;
  }

  onSearch() {
    this.initPowersData(this.farmsId);
  }

  initPowersData(ids: number[]) {
    if (this.farms != null && this.farms.length > 0) {
      let startT: Date, endT: Date, dateType: number, powerType: number[] = [1, 2];
      if (this.active === 3) {
        endT = new Date(this.currentYear);
        startT = new Date(this.startYear);
        dateType = 3;
        if (startT.getTime() === endT.getTime()) {
          alert('时间不能相同');
          return;
        }
        if (startT > endT) {
          alert('开始时间不能大于结束时间');
          return;
        }
      }
      else if (this.active === 2) {
        startT = new Date(this.startYear + '-' + this.startMonth);
        endT = new Date(this.currentYear + '-' + this.currentMonth);
        dateType = 2;
        if (startT.getTime() === endT.getTime()) {
          alert('时间不能相同');
          return;
        }
        if (startT > endT) {
          alert('开始时间不能大于结束时间');
          return;
        }
      } else {
        startT = this.startDay;
        endT = this.currentDay;
        dateType = 1;
        if (startT.getTime() === endT.getTime()) {
          alert('时间不能相同');
          return;
        }
        if (startT > endT) {
          alert('开始时间不能大于结束时间');
          return;
        }
      }

      this.quotaRankService.getPowersDeviation(ids, startT, endT, dateType, [1, 7])
        .then(res => {
          this.powersDate = [];
          this.powersMonth = [];
          this.powersYear = [];
          if (res && res.length) {
            if (dateType === 1) {   // 日
              this.powersFilters([...res], dateType)
            } else if (dateType === 2) {  // 月
              const monthFilter: PowerDeviation[] = [...res];
              monthFilter.forEach(o => {
                const date = o.date.toString().split('-');
                o.date = date[0] + '-' + date[1];
              })
              this.powersFilters([...monthFilter], dateType);
            } else {  // 年
              const yearFilter: PowerDeviation[] = [...res];
              yearFilter.forEach(o => {
                const date = o.date.split('-');
                o.date = date[0];
              })
              this.powersFilters([...yearFilter], dateType);
            }
          }
        })
        .catch(error => {
          console.log('app-power-forecast-deviation', error);
        });
    }

  }

  powersFilters(data: PowerDeviation[], dateType: number) {
    // 构建数据集合
    const powers = [];
    const powerDatas: PowerData[] = [];
    // 按日期将数据分组
    const list = new List([...data]);
    const groups = list.GroupBy(grouper => grouper.date, mapper => mapper);
    const dateTime = Object.getOwnPropertyNames(groups);
    dateTime.forEach(ele => {
      const elementList = new List(Object.getOwnPropertyDescriptor(groups, ele).value).ToArray();
      powers.push({
        time: ele,
        farmsPower: elementList
      });
    });
    powers.forEach(data => {
      // 日期分组后，按照风场分组；
      const tempList = data.farmsPower;
      const map = {},
        farmFilter = [];
      for (let i = 0; i < tempList.length; i++) {
        const ai = tempList[i];
        if (!map[ai.farmCode]) {
          farmFilter.push({
            farmCode: ai.farmCode,
            time: ai.date,
            powerDatas: [ai]
          });
          map[ai.farmCode] = ai;
        } else {
          for (let j = 0; j < farmFilter.length; j++) {
            var dj = farmFilter[j];
            if (dj.farmCode == ai.farmCode) {
              dj.powerDatas.push(ai);
              break;
            }
          }
        }
      }
      // 页面显示数据实体
      let powerData: PowerData = {
        date: farmFilter[0].time,
        farms: [],
        farmData: [],
      };
      // 按照风场分组后，相同风场下的数据组合成powerObj对象；
      farmFilter.forEach(o => {

        let powerObj = {
          farmCode: o.farmCode,
          farmName: o.powerDatas[0].farmName,
          powers: [
            {
              powerType: 1,
              value: 0
            },
            {
              powerType: 7,
              value: 0
            },
            {
              powerType: 0,
              value: 0
            }
          ]
        };
        // tslint:disable-next-line:no-shadowed-variable
        o.powerDatas.forEach(data => {
          if (data.powerType === 1) {
            powerObj.powers[0].value = data.value * this.ratio;
          } else if (data.powerType === 7) {
            powerObj.powers[1].value = data.value * this.ratio;
          }
        });
        powerObj.powers[2].value = Number((powerObj.powers[0].value - powerObj.powers[1].value).toFixed(2));
        powerData.farmData.push(powerObj);
        powerData.farms.push(powerObj.farmName);
      });
      powerDatas.push(powerData);
    });
    if (dateType === 1) {
      this.powersDate = [...powerDatas];
      /* this.powersDate.forEach(o => {
                o.farmData.sort(function (a, b) {
                    return a.farmName.localeCompare(b.farmName, 'zh');
                })
            }) */
    } else if (dateType === 2) {
      this.powersMonth = [...powerDatas];
      /* 	this.powersMonth.forEach(o => {
                    o.farmData.sort(function (a, b) {
                        return a.farmName.localeCompare(b.farmName, 'zh');
                    })
                }) */
    } else {
      this.powersYear = [...powerDatas];

      /* this.powersYear.forEach(o => {
                o.farmData.sort(function (a, b) {
                    return a.farmName.localeCompare(b.farmName, 'zh');
                });
            }); */
    }
    // tslint:disable-next-line:indent
  }

}

export interface PowerData {
  date: string;
  farms: string[];
  farmData: FarmData[];
}

interface FarmData {
  farmName: string;
  farmCode: string;
  powers: powerType[];
}

interface powerType {
  powerType: number;
  value: number;
}


// WEBPACK FOOTER //
// ./src/app/module/data-analysis/power-forecast-deviation/power-forecast-deviation.component.ts
